/**
 * 产品分类列表
 * 文件命名格式：zmn.模块名称.表名称.功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */

var treeGrid = null, tableId = 'zmn-table';
layui.define(['index', 'form', 'table', 'laypage', 'layedit',"treeTable", 'form'], function (exports) {
    var $ = layui.$;
    var treeTable = layui.treeTable;
    var table = layui.table;
    var form = layui.form;

    var serverClassTable = treeTable.render({
        elem: '#' + tableId,
        tree: {
            iconIndex: 0,  // 折叠图标显示在第几列
            idName: 'id',  // 自定义id字段的名称
            pidName: 'parentId',  // 自定义标识是否还有子节点的字段名称
            haveChildName: 'haveChild'  // 自定义标识是否还有子节点的字段名称
        },
        cols: [
            {field: 'name', title: '服务分类', width: 300,templet: function (d) {
                    let split = d.otherId.split("_");
                    let text='<div>';
                    let intputStr;
                    //一级分类与服务分类
                    if (split.length == 1) {
                        if (split == d.id){
                            let serverIn = $.inArray(d.id, json.servCategIds);
                            if  (serverIn>-1) {
                                intputStr = '<input type="checkbox" name="serverClassName_'+d.otherId+'" otherId="'+d.otherId+'" lay-filter="serverClassCheck" lay-skin="primary" value="' + d.id + '" title="'+ d.name + '" checked>'
                            } else {
                                intputStr = '<input type="checkbox" name="serverClassName_'+d.otherId+'" otherId="'+d.otherId+'" lay-filter="serverClassCheck" lay-skin="primary" value="' + d.id + '" title="'+ d.name + '" >'
                            }
                        }else{
                            let serverIn = $.inArray(parseInt(d.otherId), json.servCategIds);
                            let oneclassIn = $.inArray(d.id, json.categOneIds);
                            if  (oneclassIn>-1 && serverIn > -1) {
                                intputStr = '<input type="checkbox" name="oneClassName_'+d.otherId+'" otherId="'+d.otherId+'" lay-filter="oneClassCheck" lay-skin="primary" value="' + d.id + '" title="'+ d.name + '" checked>'
                            } else {
                                intputStr = '<input type="checkbox" name="oneClassName_'+d.otherId+'" otherId="'+d.otherId+'" lay-filter="oneClassCheck" lay-skin="primary" value="' + d.id + '" title="'+ d.name + '" >'
                            }
                        }
                    } else {
                        let tempIds=d.otherId.split("_");
                        let serverIn = $.inArray(parseInt(tempIds[0]), json.servCategIds);
                        let oneclassIn = $.inArray(parseInt(tempIds[1]), json.categOneIds);
                        let twoclassIn = $.inArray(d.id, json.categIds);
                        if  (twoclassIn>-1 && oneclassIn> -1 && serverIn > -1) {
                            intputStr = '<input type="checkbox" name="twoClassName_'+d.otherId+'" otherId="'+d.otherId+'" lay-filter="twoClassCheck" lay-skin="primary" value="' + d.id + '" title="'+ d.name + '" checked>'
                        } else {
                            intputStr = '<input type="checkbox" name="twoClassName_'+d.otherId+'" otherId="'+d.otherId+'" lay-filter="twoClassCheck" lay-skin="primary" value="' + d.id + '" title="'+ d.name + '" >'
                        }
                    }

                    text += intputStr;
                    text +='</div>';
                    return text;
                }},
            {field: 'id', title: 'ID', width: 100},
            {field: 'typeName', title: '类型', width: 100},
            {
                field: 'products', title: '服务产品',templet: function (d) {
                    if (d.products) {
                        let text='<div>';
                        let intputStr;
                        let lineNum = 4;
                        let initnNum = 1;
                        for (let i = 0; i < d.products.length; i++) {
                            let tempIds=d.products[i].otherId.split("_");
                            let serverIn = $.inArray(parseInt(tempIds[0]), json.servCategIds);
                            let oneclassIn = $.inArray(parseInt(tempIds[1]), json.categOneIds);
                            let twoclassIn = $.inArray(parseInt(tempIds[2]), json.categIds);
                            let productesIn = $.inArray(d.products[i].id, json.productIds);
                            if (productesIn > -1 && twoclassIn>-1 && oneclassIn> -1 && serverIn > -1) {
                                intputStr = '<input type="checkbox" name="productName_'+d.products[i].otherId+'" otherId="'+d.products[i].otherId+'" lay-filter="ckState" value="' + d.products[i].id + '" lay-skin="switch" lay-text="'+ d.products[i].name + '|'+ d.products[i].name + '" checked/>';
                            } else {
                                intputStr = '<input type="checkbox" name="productName_'+d.products[i].otherId+'" otherId="'+d.products[i].otherId+'"  lay-filter="ckState" value="' + d.products[i].id + '" lay-skin="switch" lay-text="'+ d.products[i].name + '|'+ d.products[i].name + '" />';
                            }
                            if (initnNum == lineNum) {
                                intputStr += '</br>';
                                initnNum = 1;
                            }
                            initnNum++;
                            text += intputStr;
                        }
                        text +='</div>';
                        return text;
                    }else {
                        return "";
                    }
                }
            }
        ],
        reqData: function(data, callback) {
            // 在这里写ajax请求，通过callback方法回调数据
            $.post('/coup/batch/loadServerClassData.action', function (res) {
                callback(res.data);  // 参数是数组类型
            });
        }
    });


    form.on('checkbox(serverClassCheck)', function(obj){
        let input=obj.elem;
        let otherId=$(input).attr("otherId");
        let server_id=$(input).attr("value");
        let oneclass;
        let twoclass;
        let twoAllclass=[];
        let peoductClass;
        let peoductAllClass = [];
        let item;
        let item1;
        //一级分类
        oneclass = $(input).parents().find("input[name=oneClassName_"+server_id+"]");
        oneclass.prop("checked",input.checked);
        if (oneclass.length > 0){
            //二级分类
            oneclass.each(function (index,item) {
                let one_class_id = item.value;
                twoclass = $(input).parents().find("input[name=twoClassName_"+server_id+"_"+one_class_id+"]");
                twoAllclass.push(twoclass);
                twoclass.prop("checked",input.checked);
                if (twoclass.length > 0){
                    //产品分类
                    twoclass.each(function (index, item) {
                        let two_class_id = item.value;
                        peoductClass = $(input).parents().find("input[name=productName_"+server_id+"_"+one_class_id+"_"+two_class_id+"]");
                        peoductAllClass.push(peoductClass);
                        peoductClass.prop("checked",input.checked);
                    })
                }
            })
        }

        //数据集合维护
        if (input.checked){
            //添加服务分类数据
            json.servCategIds.push2(server_id);
            oneclass.each(function (index,item) {
                json.categOneIds.push2(item.value)
            });
            console.log(twoclass);
            twoAllclass.forEach(function (item, index, arr) {
                let arr1 = item.map(function (idx,ele) {
                    json.categIds.push2($(ele).val())
                });
            });

            peoductAllClass.forEach(function (item, index, arr) {
                let arr1 = item.map(function (idx,ele) {
                    json.productIds.push2($(ele).val())
                });
            });

        } else {
            json.servCategIds.remove(server_id);

            oneclass.each(function (index,item) {
                json.categOneIds.remove(item.value);
            });

            twoAllclass.forEach(function (item, index, arr) {
                let arr1 = item.map(function (idx,ele) {
                    json.categIds.remove($(ele).val())
                });
            });

            peoductAllClass.forEach(function (item, index, arr) {
                let arr1 = item.map(function (idx,ele) {
                    json.productIds.remove($(ele).val())
                });
            });
        }

        form.render();
    });

    //一级分类选择器
    form.on('checkbox(oneClassCheck)', function(obj){
        let input=obj.elem;
        let otherId=$(input).attr("otherId");
        let one_class_id=$(input).attr("value");
        let twoclass;
        let peoductClass;
        let peoductAllClass = [];

        if (input.checked){
            //服务分类
            let serverClass = $(input).parents().find("input[name=serverClassName_"+otherId+"]");
            serverClass.prop("checked",input.checked);
        }else{
           /* let oneClassdatas = $(input).parents().find("input[name=oneClassName_"+otherId+"]:checked");
            if (oneClassdatas.length <= 0) {
                //服务分类
                let serverClass = $(input).parents().find("input[name=serverClassName_"+otherId+"]");
                serverClass.prop("checked",input.checked);
            }*/
        }

        //二级分类
        twoclass = $(input).parents().find("input[name=twoClassName_"+otherId+"_"+one_class_id+"]");
        twoclass.prop("checked",input.checked);
        if (twoclass.length > 0){
            //产品分类
            twoclass.each(function (index, twoclassData) {
                let two_class_id = twoclassData.value;
                peoductClass = $(input).parents().find("input[name=productName_"+otherId+"_"+one_class_id+"_"+two_class_id+"]");
                peoductAllClass.push(peoductClass);
                peoductClass.prop("checked",input.checked);
            })
        }

        //数据集合维护
        if (input.checked){
            //添加服务分类数据
            json.servCategIds.push2(otherId);
            json.categOneIds.push2(one_class_id);
            twoclass.each(function (index,item) {
                json.categIds.push2(item.value)
            });

            peoductAllClass.forEach(function (item, index, arr) {
                let arr1 = item.map(function (idx,ele) {
                    json.productIds.push2($(ele).val())
                });
            });
        } else {
            json.categOneIds.remove(one_class_id);
            twoclass.each(function (index,item) {
                json.categIds.remove(item.value);
            });
            peoductAllClass.forEach(function (item, index, arr) {
                let arr1 = item.map(function (idx,ele) {
                    json.productIds.remove($(ele).val())
                });
            });
        }
        form.render();
    });

    //二级分类选择器
    form.on('checkbox(twoClassCheck)', function(obj){
        let input=obj.elem;
        let otherId=$(input).attr("otherId");
        let tempIds=otherId.split("_");
        let two_class_id=$(input).attr("value");
        let oneclass;
        let serverClass;
        if (input.checked){
            //一级分类
            oneclass = $(input).parents().find("input[name=oneClassName_"+tempIds[0]+"][value="+tempIds[1]+"]");
            oneclass.prop("checked",input.checked);

            //服务分类
            serverClass = $(input).parents().find("input[name=serverClassName_"+tempIds[0]+"]");
            serverClass.prop("checked",input.checked);

        }else{
           /* let twoClassdatas = $(input).parents().find("input[name=twoClassName_"+otherId+"]:checked");
            if (twoClassdatas.length <= 0) {
                //一级分类
                let oneclass = $(input).parents().find("input[name=oneClassName_"+tempIds[0]+"][value="+tempIds[1]+"]");
                oneclass.prop("checked",input.checked);

                let oneClassdatas = $(input).parents().find("input[name=oneClassName_"+tempIds[0]+"]:checked");
                if (oneClassdatas.length <= 0) {
                    //服务分类
                    let serverClass = $(input).parents().find("input[name=serverClassName_"+tempIds[0]+"]");
                    serverClass.prop("checked",input.checked);

                }
            }*/
        }

        //产品分类
        let peoductClass = $(input).parents().find("input[name=productName_"+otherId+"_"+two_class_id+"]");
        peoductClass.prop("checked",input.checked);

        //数据集合维护
        if (input.checked){
            //添加服务分类数据
            json.servCategIds.push2(tempIds[0]);
            json.categOneIds.push2(tempIds[1]);
            json.categIds.push2(two_class_id);
            peoductClass.each(function (index,item) {
                json.productIds.push2(item.value)
            });
        } else {
            json.categIds.remove(two_class_id);
            peoductClass.each(function (index,item) {
                json.productIds.remove(item.value);
            });
        }
        form.render();
    });

    /**
     * 返回指定值在数组中的索引
     * @param val
     * @returns {number}
     */
    Array.prototype.indexOf = function(val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };

    Array.prototype.push2 =function(val){
        let index = this.indexOf(val);
        if (index < 0) {
            this.push(val);
        }
    };

    /**
     * 删除数组中指定的元素
     * @param val
     */
    Array.prototype.remove = function(val) {
        let index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };

    // 启用/停用（单个）
    form.on('switch(ckState)', function(obj){
        let input=obj.elem;
        let checked=obj.elem.checked;
        let otherId=$(input).attr("otherId");
        let tempIds=otherId.split("_");
        let serviceCategoryId=tempIds[0];
        let levelOneId=tempIds[1];
        let levelTwoId=tempIds[2];
        let levelOneTR=$(input).parent().parent().parent().parent().parent();//一级分类TR
        let tbody=$(levelOneTR).parent();//表格的tbody
        let levelTwoCheckBox=$(tbody).find("input[name=twoClassName_"+serviceCategoryId+"_"+levelOneId+"][value="+levelTwoId+"]")//一级分类的checkbox;
        let levelOneCheckBox=$(tbody).find("input[name=oneClassName_"+serviceCategoryId+"][value="+levelOneId+"]");//二级分类的checkbox
        let levelServiceCategoryCheckBox=$(tbody).find("input[name=serverClassName_"+serviceCategoryId+"]");//服务分类的checkbox
        let levelTwoProducts=$(levelOneTR).find("td[data-field=products]").find("input[type=checkbox]");
        // let levelOneProducts=$(levelOneCheckBox).parent();
        //let someOneLevelTwoProducts=true;//某个二级分类下的所有产品是否都没被选中
        // let someOneLevelOneProducts=true;//某个一级分类下的产品是否都没被选中
        /*levelTwoProducts.each(function(i,o){
            if(o.checked){
                someOneLevelTwoProducts=false;
            }
        });*/
        if(checked){
            $(levelTwoCheckBox).prop("checked",true);
            $(levelOneCheckBox).prop("checked",true);
            $(levelServiceCategoryCheckBox).prop("checked",true);
            //console.log("添加产品前的json:"+JSON.stringify(json));
            json.productIds.push(obj.elem.value);
            json.categOneIds.push(levelOneId);
            json.categIds.push(levelTwoId);
            json.servCategIds.push(serviceCategoryId);
            //console.log("添加产品后的json:"+JSON.stringify(json));
        }else{
            //console.log("删除产品前的json:"+JSON.stringify(json));
            json.productIds.remove(obj.elem.value);
            //json.categOneIds.remove(levelOneId);
            //json.categIds.remove(levelTwoId);
            //json.servCategIds.remove(serviceCategoryId);
            //console.log("删除产品后的json:"+JSON.stringify(json));
        }/*else if(someOneLevelTwoProducts){
            $(levelTwoCheckBox).prop("checked",false);
        }else if(someOneLevelOneProducts){
            $(levelOneCheckBox).prop("checked",false);
            $(levelServiceCategoryCheckBox).prop("checked",false);
        }*/


        /*//第一个父节点Id
        let fPid=$(tr).attr("data-pid");
        //判断是否所有产品的checkbox都被选中
        let products=$(tr).find("td[data-field=products]").find("input[type=checkbox]");
        let cancelAll=true;//是否取消对应的一级分类和服务分类的勾选
        products.each(function(i,o){
            if(o.checked){
                cancelAll=false;
            }
        });
        if(fPid){
            let tbody=$(tr).parent();
            let fTrs=$(tbody).find('tr[data-id='+levelOneId+']');
            let fTr;
            $(fTrs).each(function(){
                let pid=$(this).attr("data-pid");
                if(pid===serviceCategoryId){
                    fTr=this;
                }

            });
            let sTr=$(tbody).find('tr[data-id='+serviceCategoryId+']');
            if(checked){
                $(tr).find("td[data-type=checkbox]").find("input[type=checkbox]").prop("checked",true);
                $(fTr).find("td[data-type=checkbox]").find("input[type=checkbox]").prop("checked",true);
                $(sTr).find("td[data-type=checkbox]").find("input[type=checkbox]").prop("checked",true);
            }else if(cancelAll){
                $(tr).find("td[data-type=checkbox]").find("input[type=checkbox]").prop("checked",false);
                $(fTr).find("td[data-type=checkbox]").find("input[type=checkbox]").prop("checked",false);
                $(sTr).find("td[data-type=checkbox]").find("input[type=checkbox]").prop("checked",false);
            }

        }*/

        form.render();

    });

    //对外暴露的接口
    exports('batch_server_class', {});
});
